import React, { Component } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Row, Col, Form, Input, Select, Button, Collapse } from 'antd';
import ReactToPrint from 'react-to-print';
import AntdDatePicker from '@/components/AntdDatePicker';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import styles from '@/pages/Operate.less';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import prompt from '@/components/Prompt';
import AntdUpload from '@/components/AntdUpload';
import { formatFile } from '@/pages/Common/common';
import { queryFileList, filterAddFile, filterDeteteFile } from '@/utils/common';
import PaperInfo from './PaperInfo';
import AntdSelectRegion from '@/components/AntdSelectRegion';
import SearchSelect from '@/components/SearchSelect';
import FileReader from '@/components/FileReader';
const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const Panel = Collapse.Panel;
const dateFormat = 'YYYY-MM-DD';
const columnsCompany = [
  {
    title: '公司',
    dataIndex: 'customerName',
    width: '50%',
  },
  {
    title: '代码',
    dataIndex: 'customerCode',
    width: '50%',
  },
];

@connect(({ tmsDriver, common, loading }) => ({
  tmsDriver,
  ownCompany: common.ownCompany,
  dictObject: common.dictObject,
  selectAreaById: common.selectAreaById,
  loading: loading.effects['tmsDriver/selectDetails'],
}))
@Form.create()
export default class UpdateForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      selectedRows: [],
      visible: false,
      fileList: [],
      deleteFileIds: [],
      activeKey: ['1', '2', '3'],
      titleType: 'add',
      disabled: false,
    };
    this.fileList = [];
  }

  componentDidMount() {
    const {
      dispatch,
      match: {
        params: { id },
      },
    } = this.props;
    if (id) {
      this.getSelectDetails(id);
      this.queryFileList(id);
    } else {
      this.props.form.resetFields();
    }

    // 准驾车型
    dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'allow-vehicle-models' },
    });
    //关系：
    dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'driver-contact-re' },
    });
  }

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'DRIVER_PORTRAIT' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ headPortraitToken: data });
      },
    });
  };

  //详情信息：
  getSelectDetails = ID => {
    const { form } = this.props;
    this.props.dispatch({
      type: 'tmsDriver/selectDetails',
      payload: { id: ID },
      callback: () => {
        // this.setState({
        //   company: [{ id: data.mdsCompanyId, mdsCompanyName: data.mdsCompanyName }],
        // });
        // data.headPortraitFileId && data.headPortrait && this.setFileList(data);
      },
    });
  };
  getSelectList = (type, val) => {
    const { dispatch } = this.props;
    let params = {};
    if (type == 'search') {
      params = val;
    }
    dispatch({
      type: 'tmsDriver/selectList',
      payload: params,
    });
  };

  //保存基本信息：
  saveBasicInfo = e => {
    e.stopPropagation();
    const { fileList, deleteFileIds } = this.state;
    const {
      tmsDriver: { selectDetails },
      match: {
        params: { id },
      },
      dispatch,
    } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      const {
        address,
        contactAddress,
        domicileAddress,
        contactBankNo,
        contactPhone,
        emergencyContact,
        linkAddress2,
        relationCode,
        headPortraitToken,
        remarks2,
        ...value
      } = values;

      if (headPortraitToken && headPortraitToken.length === 1) {
        value.headPortraitToken = filterAddFile(headPortraitToken)[0];
      }
      value.deleteFileIds = filterDeteteFile(headPortraitToken, this.fileList);

      value.contact = {
        linkAddress: linkAddress2,
        contactBankNo,
        contactPhone,
        emergencyContact,
        relationCode,
        remarks: remarks2,
      };
      if (address) {
        value.province = address[0];
        value.city = address[1];
        value.district = address[2];
        value.street = address[3];
      }
      //紧急联系人
      if (contactAddress) {
        value.contact.province = contactAddress[0];
        value.contact.city = contactAddress[1];
        value.contact.district = contactAddress[2];
        value.contact.street = contactAddress[3];
      }
      //户籍地址
      if (domicileAddress) {
        value.domicileProvince = domicileAddress[0];
        value.domicileCity = domicileAddress[1];
        value.domicileDistrict = domicileAddress[2];
        value.domicileStreet = domicileAddress[3];
      }
      //编辑时传入车辆id
      if (id) {
        value.contact.id = selectDetails[id].contact ? selectDetails[id].contact.id : '';
        value.id = id;
      }
      this.props.dispatch({
        type: 'tmsDriver/driverOperate',
        payload: value,
        callback: res => {
          this.getSelectList();
          dispatch({
            type: 'tmsDriver/selectDetails',
            payload: { id: res },
            callback: data => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              //新增页变编辑页
              if (!id) {
                dispatch({
                  type: 'common/setTabsName',
                  payload: {
                    id: res,
                    name: data.name,
                    isReplaceTab: true,
                  },
                  callback: result => {
                    if (result) {
                      router.push(`/carBasic/driverList/edit-form/${res}`);
                    }
                  },
                });
              } else {
                this.queryFileList(id);
              }
            },
          });
        },
      });
    });
  };

  // 设置图片
  setFileList = data => {
    const fileList = [{ id: data.headPortraitFileId, fileUrl: data.headPortrait }];
    this.setState({ fileList });
  };

  // 上传图片
  handleChangeFirst = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemoveFirst = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };

  infoHandleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  //打开新增、编辑证件弹窗：
  showDetail = (e, type, id) => {
    e && e.stopPropagation();
    if (type == 'add' && !id) {
      prompt({ content: '请先新增司机，再新增证件', type: 'warn' });
      return;
    }
    this.setState({
      visible: true,
      titleType: type,
    });
  };
  // getValue = values => {
  //   this.setState({
  //     company: values,
  //   });
  // };

  render() {
    const {
      selectedRowKeys,
      selectedRows,
      visible,
      fileList,
      selectedPaperId,
      titleType,
      disabled,
    } = this.state;
    const {
      form: { getFieldDecorator },
      ownCompany,
      dictObject,
      selectAreaById,
      match: {
        params: { id },
      },
      tmsDriver: { selectDetails, papersList },
      loading,
    } = this.props;
    let details = {};
    let papersListDetails = {};
    if (id) {
      details = selectDetails[id];
      papersListDetails = papersList[id];
    }

    const hasSelected = selectedRowKeys.length > 0;

    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{details && id ? details.name : '新增司机'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={details && id ? codes.edit : codes.add}
          />
        ) : (
          <Button.Group>
            <AdButton
              type="primary"
              onClick={e => this.saveBasicInfo(e)}
              text="保存"
              code={details && id ? codes.edit : codes.add}
            />
            {details && id && (
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="取消"
                code={details && id ? codes.edit : codes.add}
              />
            )}
          </Button.Group>
        )}
      </div>
    );
    const genExtraCertificatesInfo = () => (
      <div>
        <AdButton
          type="primary"
          onClick={e => this.showDetail(e, 'add', id)}
          text="新增"
          code={codes.addPaper}
        />
      </div>
    );
    const InfoParams = {
      id: id,
      type: 'list',
      loading,
      showDetail: this.showDetail,
      change: this.handleStandardTableChange,
      handleCancel: this.infoHandleCancel,
      titleType,
    };
    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 12,
      border: 0,
      overflow: 'hidden',
    };
    let basicAddress = [];
    let basicAddressSe = [];
    let DomicileAddress = [];
    if (details) {
      if (details.province) {
        basicAddress.push(details.province);
      }
      if (details.city) {
        basicAddress.push(details.city);
      }
      if (details.district) {
        basicAddress.push(details.district);
      }
      if (details.street) {
        basicAddress.push(details.street);
      }

      if (details.domicileProvince) {
        DomicileAddress.push(details.domicileProvince);
      }
      if (details.domicileCity) {
        DomicileAddress.push(details.domicileCity);
      }
      if (details.domicileDistrict) {
        DomicileAddress.push(details.domicileDistrict);
      }
      if (details.domicileStreet) {
        DomicileAddress.push(details.domicileStreet);
      }

      if (details.contact && details.contact.province) {
        basicAddressSe.push(details.contact.province);
      }
      if (details.contact && details.contact.city) {
        basicAddressSe.push(details.contact.city);
      }
      if (details.contact && details.contact.district) {
        basicAddressSe.push(details.contact.district);
      }
      if (details.contact && details.contact.street) {
        basicAddressSe.push(details.contact.street);
      }
    }

    basicAddress = basicAddress.length > 0 ? basicAddress.join(',') : '';
    basicAddressSe = basicAddressSe.length > 0 ? basicAddressSe.join(',') : '';
    DomicileAddress = DomicileAddress.length > 0 ? DomicileAddress.join(',') : '';

    return (
      <div className={styles.CollapseUpdate} id="driverPage" ref={el => (this.refs = el)}>
        <PageHeaderWrapper title={this.props.type == 'add' ? '新建司机' : genExtraBasicInfo()}>
          {/* <ReactToPrint trigger={() => <AdButton text="打印" />} content={() => this.refs} /> */}
          <Collapse
            activeKey={this.state.activeKey}
            onChange={key => this.callback(key)}
            bordered={false}
          >
            <Panel header="基础信息" key="1" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="司机姓名">
                        {getFieldDecorator('name', {
                          rules: [{ required: true, message: '' }],
                          initialValue: details ? details.name : '',
                        })(<Input placeholder="请输入司机姓名" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="英文名">
                        {getFieldDecorator('engName', {
                          initialValue: details ? details.engName : '',
                        })(<Input placeholder="请输入英文名" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="身份证号">
                        {getFieldDecorator('idCard', {
                          rules: [{ required: true, message: '' }],
                          initialValue: details ? details.idCard : '',
                        })(<Input placeholder="请输入身份证号" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="工号">
                        {getFieldDecorator('workerNo', {
                          initialValue: details ? details.workerNo : '',
                        })(<Input placeholder="请输入工号" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="准驾车型">
                        {getFieldDecorator('allowVehicleType', {
                          initialValue: details ? details.allowVehicleType : undefined,
                        })(
                          <Select placeholder="请选择" allowClear={true} disabled={disabled}>
                            <Option value="">请选择</Option>
                            {dictObject['allow-vehicle-models'] &&
                              dictObject['allow-vehicle-models'].map(item => (
                                <Option key={item.code}>{item.value}</Option>
                              ))}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>

                    <Col md={12} sm={24}>
                      <Form.Item label="籍贯">
                        {getFieldDecorator('nativePlace', {
                          initialValue: details ? details.nativePlace : '',
                        })(<Input placeholder="请输入籍贯" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="公司">
                        {getFieldDecorator('mdsCompanyId', {
                          rules: [{ required: true, message: '' }],
                          initialValue: details ? details.mdsCompanyId : undefined,
                        })(
                          <Select
                            style={{ width: '100%' }}
                            showSearch
                            disabled={disabled}
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            placeholder="请选择"
                          >
                            {ownCompany.map((v, i) => {
                              return (
                                <Option key={i} value={v.customerCode}>
                                  {v.customerName}
                                </Option>
                              );
                            })}
                          </Select>

                          //   <SearchSelect
                          //     dataUrl="mds/d-customer/selectCompany"
                          //     // url="tms/tms-upkeep/selectVehicleView_s" // selectedData只只有id时需要传url
                          //     selectedData={this.state.company} // 选中值
                          //     multiple={false} // 是否多选
                          //     showValue="mdsCompanyName"
                          //     searchName="mdsCompanyName"
                          //     columns={columnsCompany} // 表格展示列
                          //     onChange={this.getValue} // 获取选中值
                          //     scrollX={480}
                          //     id="tmsDriver_1"
                          //   />
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="银行卡号">
                        {getFieldDecorator('bankNo', {
                          initialValue: details ? details.bankNo : '',
                        })(<Input placeholder="请输入银行卡号" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="联系电话1">
                        {getFieldDecorator('phoneNumOne', {
                          rules: [{ required: true, message: '请输入联系电话1' }],
                          initialValue: details ? details.phoneNumOne : '',
                        })(<Input placeholder="请输入联系电话1" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="联系电话2">
                        {getFieldDecorator('phoneNumTwo', {
                          initialValue: details ? details.phoneNumTwo : '',
                        })(<Input placeholder="请输入联系电话2" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24} sm={24}>
                      <Form.Item label="微信号">
                        {getFieldDecorator('wxNo', {
                          initialValue: details ? details.wxNo : '',
                        })(<Input placeholder="请输入微信号" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="邮箱">
                        {getFieldDecorator('email', {
                          initialValue: details ? details.email : '',
                        })(<Input placeholder="请输入邮箱" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="开户行">
                        {getFieldDecorator('bankName', {
                          initialValue: details ? details.bankName : undefined,
                        })(<Input placeholder="请输入开户行" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="户籍所在地">
                        {getFieldDecorator('domicileAddress', {
                          initialValue: DomicileAddress,
                        })(
                          <AntdSelectRegion
                            url="mds/mds-location-area/selectAreaById"
                            paramsLabel="id"
                            label="address"
                            filter={true}
                            isParent={false}
                            disabled={disabled}
                            split=","
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="联系地址">
                        {getFieldDecorator('address', {
                          initialValue: basicAddress,
                        })(
                          <AntdSelectRegion
                            url="mds/mds-location-area/selectAreaById"
                            paramsLabel="id"
                            disabled={disabled}
                            label="address"
                            filter={true}
                            isParent={false}
                            split=","
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="详细地址">
                        {getFieldDecorator('linkAddress', {
                          initialValue: details ? details.linkAddress : '',
                        })(<TextArea placeholder="请输入" rows={4} disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="备注">
                        {getFieldDecorator('remarks', {
                          initialValue: details ? details.remarks : '',
                        })(<TextArea placeholder="请输入" rows={4} disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="头像">
                        {getFieldDecorator('headPortraitToken')(
                          <FileReader urlType="tms" fileLength={1} disabled={disabled} />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Panel>
            <Panel header="紧急联系人" key="2" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="紧急联系人">
                        {getFieldDecorator('emergencyContact', {
                          initialValue:
                            details && details.contact ? details.contact.emergencyContact : '',
                        })(<Input placeholder="请输入紧急联系人" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="关系">
                        {getFieldDecorator('relationCode', {
                          initialValue:
                            details && details.contact ? details.contact.relationCode : undefined,
                        })(
                          <Select placeholder="请选择" allowClear={true} disabled={disabled}>
                            <Option value="">请选择</Option>
                            {dictObject['driver-contact-re'] &&
                              dictObject['driver-contact-re'].map(item => (
                                <Option key={item.code}>{item.value}</Option>
                              ))}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="联系电话">
                        {getFieldDecorator('contactPhone', {
                          initialValue:
                            details && details.contact ? details.contact.contactPhone : '',
                        })(<Input placeholder="请输入联系电话" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="银行卡号">
                        {getFieldDecorator('contactBankNo', {
                          initialValue:
                            details && details.contact ? details.contact.contactBankNo : '',
                        })(<Input placeholder="请输入银行卡号" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="开户行">
                        {getFieldDecorator('contactBankName', {
                          initialValue:
                            details && details.contact
                              ? details.contact.contactBankName
                              : undefined,
                        })(<Input placeholder="请输入开户行" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="联系地址">
                        {getFieldDecorator('contactAddress', {
                          initialValue: basicAddressSe,
                        })(
                          <AntdSelectRegion
                            url="mds/mds-location-area/selectAreaById"
                            paramsLabel="id"
                            label="address"
                            filter={true}
                            isParent={false}
                            split=","
                            disabled={disabled}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="详细地址">
                        {getFieldDecorator('linkAddress2', {
                          initialValue:
                            details && details.contact ? details.contact.linkAddress : '',
                        })(<Input placeholder="请输入" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="备注">
                        {getFieldDecorator('remarks2', {
                          initialValue: details && details.contact ? details.contact.remarks : '',
                        })(<TextArea placeholder="请输入" rows={4} disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Panel>
            <Panel
              header="证件信息"
              key="3"
              style={customPanelStyle}
              // extra={genExtraCertificatesInfo()}
            >
              <PaperInfo {...InfoParams} visible={visible} data={papersListDetails} />
            </Panel>
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
